package middleware

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"react-blog-server/common/auth"
	"react-blog-server/common/base"
	"strings"
)

func CheckJWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("Authorization")
		if token == "" || len(token) == 0 {
			c.Abort()
			c.JSON(http.StatusOK, gin.H{"code": http.StatusUnauthorized, "message": "请求未携带token，无权限访问"})
			return
		}
		claims, err := auth.ParseToken(token)
		if err != nil {
			if strings.Contains(err.Error(), "expired") {
				// 若过期，调用续签函数
				newToken, _ := auth.RenewToken(claims)
				if newToken != "" {
					log.Printf("续签token：%s", newToken)
					c.Header("setNewToken", newToken)
					c.Request.Header.Set("Authorization", newToken)
					c.Set(base.UserContextKey, claims)
					c.Next()
					return
				}
			}
			// Token验证失败或续签失败直接拒绝请求
			c.Abort()
			c.JSON(http.StatusOK, gin.H{"code": http.StatusUnauthorized, "message": err.Error()})
			return
		}
		c.Set(base.UserContextKey, claims)
		c.Next()
	}
}
